/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.core;

import org.latestbit.smartobjects.coders.CallInterfaceOperationRequest;
import org.latestbit.smartobjects.coders.CallInterfaceOperationResponse;
import org.latestbit.smartobjects.io.ResizableByteBuffer;
import org.latestbit.smartobjects.network.ConnectionHandler;
import org.latestbit.smartobjects.network.INetworkCommand;

public class DefaultCommandProcessorHandler implements ICommandProcessorHandler {

	private CommandProcessor processor;

	public DefaultCommandProcessorHandler(CommandProcessor processor) {
		this.processor = processor;
	}
	
	@Override
	public boolean isCommandIdSupported(ConnectionHandler handler, INetworkCommand request) {
		return true;
	}

	@Override
	public void onRequestReceived(ConnectionHandler handler, INetworkCommand request) {
		if ( request.getCommandId() == CallInterfaceOperationRequest.COMMAND_ID ) {
			
			CallInterfaceOperationRequest crequest = new CallInterfaceOperationRequest(request);
			try {
				crequest.deserialize();
				crequest.getBuffer().getBuffer().clear();
				ResizableByteBuffer writeBuffer = crequest.getBuffer();
			
				CallInterfaceOperationResponse callResponse = crequest.createResponse(writeBuffer);
				callResponse.setExceptionFlag(true);
				callResponse.setExceptionMessage ( "Unable to found any skeleton to process request");
				callResponse.setExceptionInterfaceId ( "SmartBusSystemException" );

				callResponse.beginSerialize();
				callResponse.finishSerialize();

			
				this.processor.sendResponse(handler, callResponse);
			}
			catch( Exception ex) {
				// ex.printStackTrace();
			}	
			
		}
	}

	@Override
	public void onResponseReceived(ConnectionHandler handler,
			INetworkCommand request, INetworkCommand response, Object userObject) {}

	@Override
	public void onResponseTimeout(INetworkCommand request, Object userObject) {}

}
